import { Injectable, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserLikeEntity } from './entities/user-like.entity';
import { PostEntity } from 'src/post/entities/post.entity';

@Injectable()
export class UserLikeService {
  constructor(
    @InjectRepository(UserLikeEntity)
    private likeRepo: Repository<UserLikeEntity>,
    @InjectRepository(PostEntity)
    private postRepo: Repository<PostEntity>,
  ) {}

  async like(postId: number, userId: number) {
    const exist = await this.likeRepo.findOne({
      where: {
        post: { id: postId },
        user: { id: userId },
      },
    });
    if (exist) throw new ForbiddenException('你已经点过赞了');

    await this.likeRepo.save({
      post: { id: postId },
      user: { id: userId },
    });

    await this.postRepo.increment({ id: postId }, 'likeCount', 1);
    return { message: '点赞成功' };
  }

  async getLikedPosts(userId: number) {
    const likes = await this.likeRepo.find({
      where: { user: { id: userId } },
      relations: ['post'],
    });
    return likes.map(like => like.post);
  }
}
